package org.whb.org.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.whb.basic.exception.BusinessException;
import org.whb.basic.service.impl.BaseServiceImpl;
import org.whb.basic.util.MD5Utils;
import org.whb.basic.util.StrUtils;
import org.whb.org.domain.Employee;
import org.whb.org.domain.Shop;
import org.whb.org.mapper.EmployeeMapper;
import org.whb.org.mapper.ShopMapper;
import org.whb.org.service.IShopService;
import org.whb.user.domain.Logininfo;
import org.whb.user.mapper.LogininfoMapper;

@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;


    @Override
    public void settlement(Shop shop) {
        //判断用户信息
        //1、判断信息是否为空
        if(StringUtils.isEmpty(shop)){
            throw new BusinessException("请输入商铺和管理员信息");
        }

        //2、判断用户是否已经存在
        Employee admin = shop.getAdmin();
        Employee employee=employeeMapper.loadByUsername(admin.getUsername());
        if (employee!=null){
            throw new BusinessException("该用户已存在，请直接登录！");
        }

        //3、判断确认密码是否与输入密码相同
        if(!admin.getPassword().equals(admin.getComfirmPassword())){
            throw new BusinessException("两次输入密码不一致，请重新输入！");
        }

        //密码加密
        //生成盐值
        String salt = StrUtils.getComplexRandomString(32);
        //加密加盐
        String password = MD5Utils.encrypByMd5(admin.getPassword() + salt);
        admin.setSalt(salt);
        admin.setPassword(password);

        //存入信息
        //将employee转为logininfo对象
        Logininfo logininfo=employee2Logininfo(admin);
        logininfoMapper.save(logininfo);
        admin.setLogininfo_id(logininfo.getId());

        //1、存入管理员信息，返回id
        employeeMapper.save(admin);


        //2、存入商铺信息，返回店铺id
        shop.setAdmin(admin);
        shopMapper.save(shop);
        //3、修改管理员信息（存入shop_id）
        admin.setShop_id(shop.getId());
        employeeMapper.update(admin);
    }

    private Logininfo employee2Logininfo(Employee admin) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(admin, logininfo);
        logininfo.setType(0);
        return logininfo;
    }
}
